package engine.newUi
{
	import engine.data.ModelLocator;
	import engine.flag.GameDefine;
	import engine.flag.ResourcesPath;
	import engine.logic.ChatFilterLogic;
	import engine.net.messages.CustomToServerFlag;
	import engine.net.mgr.SystemSender;
	import engine.tip.TipsMainLogic;
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	import flash.text.StyleSheet;
	
	import newx.com.config.StaticIni;
	import newx.com.control.NxClip;
	import newx.com.control.text.NxLabel;
	import newx.com.control.window.NxWindowEvent;
	
	/**
	 * 查看邮件逻辑 
	 * @author liuel
	 * 
	 */	
	public class SeeMailLogic
	{
		private static var	_self :SeeMailLogic;
		private var _ui:SeeMailUI;
		private var _item:Object;
		private var _mail:Array;
		private var _mailId:String;
		
		//接收邮件的ren
		private var _addressee:String;
		//标题
		private var _title:String;
		private var img:NxClip;
		private var itemMC:MovieClip;
		public static function getInstance():SeeMailLogic
		{
			if(_self == null)
			{
				_self=new SeeMailLogic();
			}
			return _self;
		}
		public function SeeMailLogic()
		{
		}
		public function Init() : void
		{
			_ui =SeeMailUI.getInstance();
			_ui.gridGroup.buttonMode = true;
			initGroup();
			var txtStyle	:StyleSheet	=	new StyleSheet();
			
			txtStyle.setStyle("a:link"		,{color:"#"+StaticIni.getIniVar("Css_a_NpcTalk","link"),textDecoration:"underline"});
			txtStyle.setStyle("a:visited"	,{color:"#"+StaticIni.getIniVar("Css_a_NpcTalk","visited")});
			txtStyle.setStyle("a:hover"	,{color:"#"+StaticIni.getIniVar("Css_a_NpcTalk","hover"),textDecoration:"none"});
			
			_ui.txtContent.styleSheet	=	txtStyle;
			_ui.txtContent.color =0xffffff;
			
		}
		
		/**
		 * 读发件箱邮件
		 * @param $mail		邮件
		 * 
		 */
		public function seeSendMail($mail:Object):void
		{
			_mail = [];
			_ui.txtContent.setScroll(0)
			var filter : ChatFilterLogic = ChatFilterLogic.getInstance();
			
			_ui.labSender.htmlStr = ModelLocator.getInstance().scene.Role.GetPropertiesEx("Name");
			_ui.labAddressee.htmlStr=$mail[0];
			_ui.labTitle.htmlStr=	filter.filter($mail[2]);
			_ui.txtContent.htmlStr=	filter.filter($mail[3]);
			_ui.labTime.htmlStr=$mail[1].substr(1,10);
			
			_ui.gridGroup.visible = false;
			_ui.btnGet.visible=false;
			_ui.labAccessoriesTip.visible =false;
			_ui.btnGet.enabled = false;
			_ui.btnRevert.enabled = false;
			
			_ui.showOrHide();
		}
		
		/**
		 * 读收件箱邮件
		 */
		public function seeMail($mail:Object):void{
			_ui.gridGroup.visible = true;
			_ui.btnGet.visible=true;
			_ui.labAccessoriesTip.visible =true;
			_mail = [];
			_mail = $mail as Array;
			if(_mail== null)return;
			_ui.txtContent.setScroll(0)
			//改变状态，告诉服务器，我读邮件了
			SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_LETTER_READ,$mail[3]);
			
			_ui.btnGet.enabled = false;
			
			_ui.labAddressee.htmlStr = ModelLocator.getInstance().scene.Role.GetPropertiesEx("Name");
			_ui.labTime.htmlStr=_mail[2];
			
			var filter : ChatFilterLogic = ChatFilterLogic.getInstance();
			//邮件类型
			var mailType:int = $mail[4];
			isRevertMail(mailType);
			
			//检查邮件类型
			checkMailType(mailType);
			
			if(mailType == GameDefine.Letter_Type_Common){
				_ui.gridGroup.visible = false;
				_ui.btnGet.visible=false;
				_ui.labAccessoriesTip.visible =false;
				_ui.labSender.htmlStr=_mail[0];
				_ui.labTitle.htmlStr= filter.filter(_mail[5]);
				_ui.txtContent.htmlStr= filter.filter(_mail[6]);
			}
			else if(mailType == GameDefine.Letter_Type_SysTemAuto)
			{//系统
				_ui.labSender.htmlStr = getTip(_mail[0]);
				_ui.labTitle.htmlStr = getTip(_mail[5]);
				_ui.txtContent.htmlStr = getTip(_mail[6]);
			}
			else if(mailType == GameDefine.Letter_Type_Pklist || 
				mailType == GameDefine.Letter_Type_ROB || mailType == GameDefine.Letter_Type_CampBattle)
			{
				_ui.labSender.htmlStr=StaticIni.getSwfLangStr(_mail[0]);
				_ui.labTitle.htmlStr = StaticIni.getSwfLangStr(_mail[5]);
				var titles:String;
				if((_mail[6]).indexOf("#") != -1){
					var pattern:RegExp = /,/;  
					titles = _mail[6].replace(pattern,"_");
					var contents:Array =titles.split("#");
					var tip:Array = [];
					for(var j:int = 1;j< contents.length;j++){
						tip.push(contents[j]);
					}
					_ui.txtContent.htmlStr = StaticIni.getSwfLangStrVar(contents.shift(),tip);
				}else{
					_ui.txtContent.htmlStr=StaticIni.getSwfLangStr(_mail[6]);
				}
			}
			else
			{
				_ui.labSender.htmlStr=StaticIni.getSwfLangStr(_mail[0]);
				_ui.labTitle.htmlStr = StaticIni.getSwfLangStr(_mail[5]);
				var title:String;
				if((_mail[6]).indexOf("#") != -1){
					var myPattern:RegExp = /,/;  
					title = _mail[6].replace(myPattern,"_");
					var content:Array =title.split("#");
					var tips:Array = [];
					for(var i:int = 1;i< content.length;i++){
						tips.push(StaticIni.getSwfLangStr(content[i]));
					}
					_ui.txtContent.htmlStr = StaticIni.getSwfLangStrVar(content.shift(),tips);
				}else{
					_ui.txtContent.htmlStr=StaticIni.getSwfLangStr(_mail[6]);
				}
			}
			
			_mailId = _mail[3];
			if(_mail[7] !=""){
				_ui.btnGet.enabled = _ui.btnGet.visible = true;
				showPhoto((_mail[7]).split(";")); 
			}
			_ui.show();
			
			//保存，回复邮件用
			_addressee =_ui. labSender.htmlStr;
			_title = _ui.labTitle.htmlStr;
			
			//把未读邮件设置为已读
			MailLogic.getInstance().readedMail(_mail);
		}
		
		private function checkMailType(type:int):void
		{
			switch(type)
			{
				case GameDefine.Letter_Type_SysTemAuto:
				case GameDefine.Letter_Type_SystemYW:
					_ui.txtContent.addLinkClickHandel( onLinkClick );
					_ui.txtContent.mouseChildren = _ui.txtContent.mouseEnabled = true;
					break;
				default:
//					_ui.txtContent.mouseChildren = _ui.txtContent.mouseEnabled = false;
					_ui.txtContent.removeLinkClickHandel();
					break;
			}
		}
		
		private function onLinkClick( str:String ):void
		{
			if( _mail[4] == GameDefine.Letter_Type_SysTemAuto 
				||	_mail[4] == GameDefine.Letter_Type_SystemYW )
			{//是系统邮件
				var url:URLRequest = new URLRequest( str );
				navigateToURL(url,"_blank");
			}
		}
		
		/**
		 *	可以回复的邮件显示回复按钮 
		 * @param mailType		邮件类型
		 * 
		 */
		private function isRevertMail(mailType : int):void
		{
			if(mailType == GameDefine.Letter_Type_Common)
			{
				_ui.btnRevert.enabled = true;
			}else
			{
				_ui.btnRevert.enabled = false;
			}
		}
		
		
		/**
		 * 获得需要显示的提示信息 
		 * 
		 */ 
		private function getTip(pList:String):String
		{
			var tArr:Array = [];
			var trueVal		:Array = pList.split("#");
			var tSize:uint	=	trueVal.length;
			
			for(var j:uint	= 0 ; j < tSize ; j ++)
			{
				var str : String = trueVal[j];
				//多场景显示;分隔场景id
				if(str.indexOf(";") != -1){
					var scenes : Array = str.split(";");
					var sceneStr:String = "";
					var leng:int = scenes.length;
					var tip : String;
					for(var i:int = 0; i< leng;i++){
						if(scenes[i] == "") continue;
						sceneStr +=  StaticIni.getSwfLangStr(scenes[i]) + ",";
					}
					tArr.push(sceneStr.substr(0,sceneStr.length - 1));
					continue;
				}
				//转
				var index : int = str.indexOf("{");
				if(index != -1) str = str.substr(1, str.length - 2);
				if(int(str) != 0 && index == -1){
					tArr.push(str);
					continue;
				}else if(int(str) != 0 && index != -1){
					tArr.push(StaticIni.getSwfLangStr(str));
					continue;
				}
				tArr.push(StaticIni.getSwfLangStr(str));
			}
			
			//说明带参数的
			if(tSize > 1){
				tArr.shift();
				return StaticIni.getSwfLangStrVar(trueVal[0],tArr);
			}else{
				return tArr.join("");
			}
			
			
		}
		
		private function showPhoto($itemList:Array):void{
			cleaItemAll();
			var leng:int = $itemList.length - 1;
			for(var i:int = 0;i < leng;i++ ){
				if(i<_ui.gridGroup.col*_ui.gridGroup.row)
				{
					addItemImage($itemList[i].split(","),i);
				}
				
			}
		}
		private function initGroup():void
		{
			var txtCount:NxLabel;
			var len:int = _ui.gridGroup.row*_ui.gridGroup.col;
			for(var i:int=0;i<len;i++)
			{
				itemMC = _ui.gridGroup.getItemByIndex(i);
				txtCount =	new NxLabel();
				
				img= new NxClip;
				img.x =	img.y =4;
				itemMC["img"]=img ;
				itemMC["Amount"] =txtCount;
				itemMC.addChild(img);
				itemMC.addChild(txtCount);
			}
			
		}
		/**
		 * 添加道具图片
		 */
		private function addItemImage($item:Array,$itemPos:int):void
		{
			
			var configID:String = $item[0];
			var item:Object = TipsMainLogic.instance.getStaticObjWithID(configID);//StaticIni.getIniObj(configID);
			if(item==null) return;
			if($item[4] != null)
			{
				var itemArray:Array	=	($item[4] as String).split("|")
			}
			
			var itemMC:MovieClip =	_ui.gridGroup.getItemByIndex($itemPos);
			
			itemMC["img"].source = ResourcesPath.getPropsURL(item["Photo"]);//"res/items/icon_"+item["Photo"]+".jpg";
			
			//当时有数量的物品时，显示物品
			if($item[1] > 1){
//				var txtCount:NxLabel =	new NxLabel();
				itemMC["Amount"].htmlStr = $item[1];
//				itemMC.addChild(txtCount);
			}
			
			itemMC["data"]	= item;
			itemMC["HoleCount"]	=	0
			var countArray:Array	=	[];
			//			for(var a:int=	0; a<10; a++)
			//			{
			//				countArray[a]	=	0;
			//			}
			if(itemArray != null)
			{
				for(var i:int = 2; i< itemArray.length; i++)
				{
					var tempStrArry:Array	=	(itemArray[i] as String).split(":");
					var propNameT	:String			=	tempStrArry[0];
					var propValT	:String			=	tempStrArry[1];
					var propT		:String			=	propNameT.substring(0,propNameT.length-1);
					switch(propT)
					{
						case "Hardines":
							itemMC["Hardiness"]				=	propValT;
							break;
						case "BindTyp":
							itemMC["BindType"]				=	propValT;
							break;
						case "HoleCoun":
							itemMC["HoleCount"]				=	Number(propValT);
							break;
						case "AddPropNo":
							var addInt:int		=	int(propNameT.substring(propNameT.length-1));
							countArray[addInt]	=	propValT;
							break;
					}	
				}
			}
			
			if(countArray.length == 0)
			{
				countArray	=	null;
			}
			itemMC["countArray"]	= countArray;
		}
		
		private function cleaItemAll():void{
			var len:int = _ui.gridGroup.row*_ui.gridGroup.col;
			for(var i:int=0;i<len;i++)
			{
				itemMC = _ui.gridGroup.getItemByIndex(i);
				itemMC["img"].source ="";
				itemMC["data"]=null;
				itemMC["Amount"].text ="";
			}
		}
		
		private function getItem(e:MouseEvent):void{
			SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_LETTER_GIFT_GET,_mailId);
			_ui.btnGet.enabled =false
			cleaItemAll();
			_ui.hide();
		}
		
		//		private function clearItemAll():void
		//		{
		//			for(var i:int = 0;i < 5;i++){
		//				clearItem(_ui.gridGroup.getItemByIndex(i));
		//			}
		//		}
		//		
		private function clearItem($itemMC:MovieClip):void
		{
			while($itemMC.numChildren > 1){
				$itemMC.removeChildAt(1);
			}
			$itemMC["data"] = null;
		}
		
		private function revertMail(e:MouseEvent):void{
			_ui.hide();
			
			MailUI.getInstance().hide();
			SendMailLogic.getInstance().revertMail(_addressee,_title);
		}
		
		private function addListener():void{
			_ui.windowBG.addEventListener(NxWindowEvent.WINDOW_CLOSE,onClose);
			_ui.btnClose.addEventListener(MouseEvent.CLICK,onClose);
			_ui.btnGet.addEventListener(MouseEvent.CLICK,getItem);
			_ui.btnRevert.addEventListener(MouseEvent.CLICK,revertMail);
			_ui.gridGroup.addItemsEvent(MouseEvent.MOUSE_OVER,onShowTip);
			_ui.gridGroup.addItemsEvent(MouseEvent.MOUSE_OUT,onHideTip);
		}
		private function removeListener():void{
			_ui.windowBG.removeEventListener(NxWindowEvent.WINDOW_CLOSE,onClose);
			_ui.btnClose.removeEventListener(MouseEvent.CLICK,onClose);
			_ui.btnGet.removeEventListener(MouseEvent.CLICK,getItem);
			_ui.btnRevert.removeEventListener(MouseEvent.CLICK,revertMail);
			_ui.gridGroup.removeItemsEvent(MouseEvent.MOUSE_OVER,onShowTip);
			_ui.gridGroup.removeItemsEvent(MouseEvent.MOUSE_OUT,onHideTip);
		}
		
		private function onClose(e:Event):void
		{
			_ui.hide();
		}
		
		public function	BeforeShow():void
		{	
			addListener();
		}
		
		public function	AfterHide():void
		{	
			cleaItemAll();
			removeListener();
		}
		private function onShowTip(e:MouseEvent):void
		{
			var itemMC:MovieClip = e.currentTarget as MovieClip;
			if(itemMC== null || itemMC["data"]==null) return;
			TipsMainLogic.instance.showMain(itemMC["data"]);
		}
		private function onHideTip(e:MouseEvent):void
		{
			TipsMainLogic.instance.hide();
		}
	}
}